package org.example.spring_frist.MessageProject.config;

import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

//就是你的问题

/**
 * 为每个数据库创建的独立配置类，将数据库和mybatis绑定
 * 在basePackages这个路径下的类是在message这个数据库中查询的
 * 使用ConfigurationProperties这个注解吧yml中的message配置读入了
 */
@Primary
@Configuration
@MapperScan(basePackages = "org.example.spring_frist.MessageProject.mapper",
        sqlSessionFactoryRef = "messageSqlSessionFactory")
public class messageConfig {
    @Bean(name = "messageDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.message")//绑定yml中的message配置信息
    public DataSource messageDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "messageSqlSessionFactory")
    public SqlSessionFactory messageSqlSessionFactory(
            @Qualifier("messageDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        //之前没加上着一段就出现了绑定问题Mapper接口路径未被扫描的 Invalid bound statement (not found)
        //即使是我在配置文件中写好了 没有扫描到xml文件 加上就好
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:MapperXml/messageWall/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "messageSqlSessionTemplate")
    public SqlSessionTemplate messageSqlSessionTemplate(
            @Qualifier("messageSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "messageTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(
            @Qualifier("messageDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
